# Standard libs
import base64
import hashlib
import logging
import urllib
import time
import datetime

# App Engine imports
from google.appengine.api import mail
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import images
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import users

# Third party imports
import json
import os, random, string
import StringIO
import re

# GData API imports
import gdata
import atom
import gdata.service
import gdata.photos.service
import gdata.spreadsheet.service

# Project specific imports
from models import Token

USERID = 'LOGIN'
PASSWORD = 'PASSWORD'
SPREADSHEET_KEY = 'KEY' # ID of photo contest spreadsheet
WORKSHEET_KEY = 'od6' # Id of default worksheet.


class DataIO(webapp.RequestHandler):
  def RenderTemplate(self, filename, dictionary):
    """Render the given template definition file with the given dictionary.

    Args:
      filename: The filename of the template to expand.
      dict: The dictionary that contains the values to populate in the template.
    """
    path = os.path.join(os.path.dirname(__file__), filename)
    self.response.headers['Content-Type'] = 'text/javascript'
    self.response.out.write(template.render(path, dictionary))


  def GetMatchesDetail(self, gd_client):
    matches = []
    q = gdata.spreadsheet.service.DocumentQuery()
    q['title'] = 'football fever 2010'
    q['title-exact'] = 'true'
    feed = gd_client.GetSpreadsheetsFeed(query=q)
    rows = gd_client.GetListFeed(SPREADSHEET_KEY, WORKSHEET_KEY).entry
    for row in rows:
      item = {}
      for key in row.custom:
        item[key] = row.custom[key].text
      matches.append(item)
    logging.error(matches)
    self.RenderTemplate('templates/matches.js', {'data': json.write(matches)})

  def GetMatchDetail(self, gd_client):
    match_id = self.request.get('matchId', '')
    json_data = {}
    self.response.headers['Content-Type'] = 'text/json'
    if match_id == '':
      self.response.out.write(json.write({'error': 'No match id?'}))
    else:
      q = gdata.spreadsheet.service.DocumentQuery()
      q['title'] = 'football fever 2010'
      q['title-exact'] = 'true'
      feed = gd_client.GetSpreadsheetsFeed(query=q)
      rows = gd_client.GetListFeed(SPREADSHEET_KEY, WORKSHEET_KEY).entry
      item = {'error': 'No item found'}
      for row in rows:
        if row.custom['matchnumber'].text == match_id:
          item = {'error': 0}
          for key in row.custom:
            item[key] = row.custom[key].text
          break
      logging.info(item)
      self.response.out.write(json.write(item))

  def GetMatches(self):
    token = Token.all().get()
    if token is None:
      gd_client = self.Login()
      self.AddOrUpdateToken(gd_client.GetClientLoginToken())
    else:
      gd_client = gdata.spreadsheet.service.SpreadsheetsService(SPREADSHEET_KEY, WORKSHEET_KEY)
      gd_client.SetClientLoginToken(token.token)
    try:
      self.GetMatchesDetail(gd_client)
    except Exception, err:
      # To handle 'Token Expired' error.
      logging.error('Error occured: ' + str(err))
      gd_client = self.Login()
      self.AddOrUpdateToken(gd_client.GetClientLoginToken())
      self.GetMatchesDetail(gd_client)

  def GetMatch(self):
    token = Token.all().get()
    if token is None:
      gd_client = self.Login()
      self.AddOrUpdateToken(gd_client.GetClientLoginToken())
    else:
      gd_client = gdata.spreadsheet.service.SpreadsheetsService(SPREADSHEET_KEY, WORKSHEET_KEY)
      gd_client.SetClientLoginToken(token.token)
    try:
      self.GetMatchDetail(gd_client)
    except Exception, err:
      # To handle 'Token Expired' error.
      logging.error('Error occured: ' + str(err))
      gd_client = self.Login()
      self.AddOrUpdateToken(gd_client.GetClientLoginToken())
      self.GetMatchDetail(gd_client)

  def AddOrUpdateToken(self, login_token):
    token = Token.all().get()
    if token is None:
      token = Token()
    token.token = login_token
    token.put()

  def Login(self):
    # Create a client class which will make HTTP requests with Google Spreadsheet server.
    gd_client = gdata.spreadsheet.service.SpreadsheetsService(SPREADSHEET_KEY, WORKSHEET_KEY)
    # Authenticate using your Google Docs email address and password.
    gd_client.email = USERID
    gd_client.password = PASSWORD
    gd_client.source = 'football-fever'
    try:
      gd_client.ProgrammaticLogin()
    except Exception, err:
      # TODO Need to handle 'Captcha Required' exception properly.
      logging.error('Error occured' + str(err))
    return gd_client

  def get(self):
    if self.request.path.startswith('/getmatches'):
      self.GetMatches()
    elif self.request.path.startswith('/getmatch'):
      self.GetMatch()
    else:
      pass

  def post(self):
    self.get()
